package ltd.hxya.novel.user.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ltd.hxya.novel.common.bean.Result;
import ltd.hxya.novel.common.utils.BaseUtils;
import ltd.hxya.novel.common.valid.SaveOperate;
import ltd.hxya.novel.common.valid.UpdateOperate;
import ltd.hxya.novel.user.entity.User;
import ltd.hxya.novel.user.service.IUserService;
import ltd.hxya.novel.user.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 *  =====================================================================================================
 *  以下为获取后台管理系统可以访问的信息
 */
@RestController
@RequestMapping("/user/admin")
public class AdminController {

    @Autowired
    private IUserService userService;

    /**
     * 获取user列表信息
     */
    @PreAuthorize("@expression.hasAuthority('user:admin:list')")
    @GetMapping("/list")
    public Result<Page<User>> userList(User user){
        //根据条件查询相关信息，并封装
        Page<User> userPage = userService.getUserList(user);
        return Result.success(userPage);
    }

    /**
     * 获取用户信息
     */
    @PreAuthorize("@expression.hasAuthority('user:admin:info')")
    @GetMapping("/userInfo/{userId}")
    public Result<User> info(@PathVariable String userId){
        User user = userService.userInfo(userId);
        return Result.success(user);
    }

    /**
     * 修改用户状态
     */
    @PreAuthorize("@expression.hasAuthority('user:admin:update')")
    @PutMapping("/changeStatus")
    public Result changeStatus(@RequestBody User user){
        userService.changeStatus(user);
        return Result.success();
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@expression.hasAuthority('user:admin:delete')")
    @DeleteMapping("/{userId}")
    public Result deleteUser(@PathVariable String userId){
        return BaseUtils.hasRow(userService.getBaseMapper().deleteById(userId));
    }

    /**
     * 添加用户
     */
    @PutMapping("/add")
    public Result addUser(@Validated(value = SaveOperate.class) @RequestBody User user) {
        userService.addUser(user);
        return Result.success();
    }

    /**
     * 修改用户信息
     */
    @PostMapping("/update")
    public Result updateUser(@Validated(value = UpdateOperate.class) @RequestBody User user){
        userService.updateUser(user);
        return Result.success();
    }

    /**
     * 管理员修改用户密码
     */
    @PostMapping("/updatePassword")
    public Result updatePassword(@NotNull(message = "id不能为空") String id, @Size(min = 6,max = 12,message = "登录密码在6到12位之间")String password){
        userService.updatePassword(id,password);
        return Result.success();
    }


}
